﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;

namespace t4tesk1
{
    class DBHelper
    {
        //数据库连接字符串
        public static string sql = "server=212.129.237.102;database=GameDB;uid=sa;pwd=Qq123456";
        //数据库连接对象
        public static SqlConnection conn = null;
        //初始化数据库连接
        public static void InitConnection()
        {
            //如果对象不存在，创建连接对象
            if (conn == null)
            {
                conn = new SqlConnection(sql);
            }
            //如果连接对象关闭，重新连接
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            //如果中断，着重启连接
            if (conn.State == ConnectionState.Broken)
            {
                conn.Close();
                conn.Open();
            }
        }
        /*
         * 增删改操作
         * 参数：sql
         * 返回值：bool
         */
        public static bool GetNonQuery(string Sql)
        {
            InitConnection();
            SqlCommand cmd = new SqlCommand(Sql, conn);
            int i = cmd.ExecuteNonQuery();
            conn.Close();
            return i > 0;
        }
        /*
         * 查询操作
         * 参数：sql
         * 返回值：SqlDataReader
         */
        public static SqlDataReader Select(string Sql)
        {
            //1.创建连接对象
            SqlConnection conn = new SqlConnection(sql);
            //2.打开连接
            conn.Open();
            //3.创建对象命令
            SqlCommand cmd = new SqlCommand(Sql, conn);
            //4.ExecuteReader执行
            return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
        }
        /*
         * 集合函数
         * 参数：sql
         * 返回值：SqlDataReader
         */
        public static object ExecuteScalar(string Sql)
        {
            //1.创建连接对象
            SqlConnection conn = new SqlConnection(sql);
            //2.打开连接
            conn.Open();
            //3.创建对象命令
            SqlCommand cmd = new SqlCommand(Sql, conn);
            object result = cmd.ExecuteScalar();
            conn.Close();
            return result;
        }
    }
}
